跳到主要内容

Springboot捕获接口Not Found异常

原文:https://javajgs.com/archives/25256

Springboot版本: 2.7.1

继承BasicErrorController

主要是重写2个方法

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

// 自定义错误处理器
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomErrorController extends BasicErrorController {

@Value("${server.error.path:${error.path:/error}}")
private String path;

// 这里idea会报错:无法自动装配。找不到 'ServerProperties' 类型的 Bean。
// 我还不懂为什么,请求大佬告知!
public CustomErrorController(ServerProperties serverProperties) {
super(new DefaultErrorAttributes(), serverProperties.getError());
}

// 重写 postman 请求时返回的json
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HashMap<String, Object> map = new HashMap<>();
map.put("result", result);
return new ResponseEntity<>(map, HttpStatus.NOT_FOUND);
}

// 重写 浏览器 请求时返回的html
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections
.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
}

请求未定义的 api 即可测试。